package jp.ac.hosei.gaedemo.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.logging.Logger;

import jp.ac.hosei.gaedemo.model.Blobstore;
import jp.ac.hosei.gaedemo.service.SchedulerService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;
import org.slim3.util.DateUtil;
import org.slim3.util.RequestMap;
import org.slim3.util.StringUtil;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;

public class UploadController extends Controller {

    private SchedulerService service = new SchedulerService();
    private final static Logger logger = Logger.getLogger(UploadController.class.getName());
    
    @Override
    public Navigation run() throws Exception {
        BlobstoreService bs = BlobstoreServiceFactory.getBlobstoreService();
        Map<String, BlobKey> blobs = bs.getUploadedBlobs(request);
        BlobKey blobKey = blobs.get("attachment");

        RequestMap rm = new RequestMap(request);
        logger.info(rm.toString());
        
        String blobKeyString = null;
        if (blobKey != null) {
            blobKeyString = blobKey.getKeyString();
            Key key = Datastore.createKey(Blobstore.class, blobKeyString);
            Blobstore blobstore = new Blobstore();
            blobstore.setKey(key);
            Datastore.put(blobstore);
        }
        // Formからの値を取り出す時にslim3既存のasStringやasDateを使うとサーバで値が取れない不具合の為
        // 現在のバージョンでは下記のとおりMapに値を一度全部書き写す必要がある。
        // その際、このクラスに定義しているasString()とasDate()を使うこと
        Map<String, Object> scheduleMap = new RequestMap(request);
        scheduleMap.put("attachmentKey", blobKeyString);
        scheduleMap.put("startDate", convertDate(asDate("startDate", "yyyy/MM/dd"), asString("startTime")));
        scheduleMap.put("endDate", convertDate(asDate("endDate", "yyyy/MM/dd"), asString("endTime")));
        scheduleMap.put("title", this.asString("title"));
        scheduleMap.put("place", this.asString("place"));
        scheduleMap.put("content", this.asString("content"));
        scheduleMap.put("comment", this.asString("comment"));
        service.createSchedule(scheduleMap);
        return redirect(basePath);
    }
    
    /**
     * 日付コンバータ
     * @param baseDate
     * @param time（hh:mm形式であること限定）
     * @return 
     * ※時間のフォーマットが固定になっている箇所は場合により改造が必要
     */
    private Date convertDate(Date baseDate, String time) {
        if (baseDate == null) {
            return null;
        } else {
            Calendar cal = Calendar.getInstance();
            cal.setTime(baseDate);
            cal.set(Calendar.HOUR, Integer.valueOf(time.substring(0, time.indexOf(":"))).intValue());
            cal.set(Calendar.MINUTE, Integer.valueOf(time.substring(time.lastIndexOf(":") + 1)).intValue());
            return cal.getTime();
        }
    }
    
    protected String asString(CharSequence name) throws NullPointerException {
        if (name == null) {
            throw new NullPointerException(
                "The name parameter must not be null.");
        }
        // slim3の既存asString()内ではgetAttribute()を用いている
        // これではサーバから値が取れない模様
        return StringUtil.toString(request.getParameter(name.toString()));
    }

    protected Date asDate(CharSequence name, String pattern)
            throws NullPointerException {
        return DateUtil.toDate(asString(name), pattern);
    }

}
